package net.test;
import java.io.*;
import java.util.HashMap;
import java.util.Map;
import org.jdom.Attribute;
import org.jdom.DocType;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.Namespace;
import org.jdom.ProcessingInstruction;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;
import java.lang.*;
import java.sql.*;

public class JdomCreateXML {

	public static void main(String[] args) throws Exception 
     {
     try
     {
    	 Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); 
 		Connection conn = DriverManager.getConnection("jdbc:sqlserver://192.168.1.21:2433;DatabaseName=test","sa","oilchem2009");
 		//设置为可更新结果集
 		Statement  stmt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
 		ResultSet rs = stmt.executeQuery("SELECT* From Test ");    	 
     //得到列的名字
    ResultSetMetaData rsmd = rs.getMetaData();
    int numColumns = rsmd.getColumnCount();
    String[] columnNames = new String[numColumns];
    for (int i = 0; i < numColumns; i++) {
     columnNames[i] = rsmd.getColumnName(i + 1);
    }
      Document doc = new Document();

    Element root = new Element("urlset" ); //创建一个元素
    Namespace ns = Namespace.getNamespace("xmlns", "http://www.sitemaps.org/schemas/sitemap/0.9");
    root.addNamespaceDeclaration(ns);
//    root.setAttribute("xmlns","http://www.sitemaps.org/schemas/sitemap/0.9");
//    root.setAttribute("xmlns:xsi","http://www.w3.org/2001/XMLSchema-instance");   
//    root.setAttribute("xsi:schemaLocation","http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd");
    
     doc.setRootElement(root); //将该元素做为根元素

    while(rs.next()){ //将查询结果取出

   Element good = new Element("good");
     root.addContent(good); //将product做为productsDetails的子元素

   for (int i=1; i<=numColumns;i++)

   { String date=rs.getString(i);   System.out.println(date); 
   Element element=new Element(rsmd.getColumnName(i)).setText(date);
   good.addContent(element);
   XMLOutputter outp = new XMLOutputter();//用于输出jdom 文档
     Format format=Format.getPrettyFormat(); //格式化文档
     format.setEncoding("GBK"); //由于默认的编码是utf-8,中文将显示为乱码，所以设为gbk
     outp.setFormat(format);
     outp.output(doc, new FileOutputStream("good.xml"));
   }

   }

     }catch(Exception e)
     {
     System.out.println(e);
     }

     }

}
